<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      <div>
        <h2 class="text-2xl font-bold">栏目管理</h2>
        <p class="text-gray-500 mt-1">管理网站所有栏目结构，支持多级栏目和排序</p>
      </div>
      
      <div class="flex flex-wrap gap-3">
        <button class="btn btn-secondary" @click="refreshCategories">
          <i class="fa fa-refresh"></i>
          <span>刷新</span>
        </button>
        <button class="btn btn-primary" @click="showAddCategoryDialog">
          <i class="fa fa-plus"></i>
          <span>新增栏目</span>
        </button>
      </div>
    </div>
    
    <!-- 栏目筛选 -->
    <div class="card p-4">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">所属站点</label>
          <select class="form-input" v-model="filters.siteId" @change="loadCategories">
            <option value="">全部站点</option>
            <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">栏目类型</label>
          <select class="form-input" v-model="filters.type" @change="filterCategories">
            <option value="">全部类型</option>
            <option value="article">文章栏目</option>
            <option value="product">产品栏目</option>
            <option value="page">单页栏目</option>
            <option value="link">链接栏目</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">栏目状态</label>
          <select class="form-input" v-model="filters.status" @change="filterCategories">
            <option value="">全部状态</option>
            <option value="active">启用</option>
            <option value="inactive">禁用</option>
          </select>
        </div>
      </div>
    </div>
    
    <!-- 栏目列表和树形结构 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 树形结构 -->
      <div class="lg:col-span-1">
        <div class="card h-full">
          <div class="p-4 border-b border-gray-100">
            <h3 class="font-medium">栏目结构</h3>
            <p class="text-sm text-gray-500 mt-1">拖拽可调整排序和层级</p>
          </div>
          
          <div class="p-4 max-h-[calc(100vh-320px)] overflow-y-auto">
            <div class="space-y-1">
              <template v-for="category in filteredCategoryTree" :key="category.id">
                <div class="category-item" :class="{'bg-primary/10': selectedCategoryId === category.id}">
                  <div class="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer hover:bg-gray-100" @click="selectCategory(category.id)">
                    <i class="fa" :class="category.children && category.children.length ? (category.expanded ? 'fa-chevron-down' : 'fa-chevron-right') : 'fa-folder-o'"></i>
                    <span>{{ category.name }}</span>
                    <span class="ml-auto badge" :class="category.status === 'active' ? 'bg-success/10 text-success' : 'bg-gray-100 text-gray-600'">
                      {{ category.status === 'active' ? '启用' : '禁用' }}
                    </span>
                  </div>
                  
                  <!-- 子栏目 -->
                  <div v-if="category.expanded && category.children && category.children.length" class="ml-4 mt-1 border-l-2 border-gray-200 pl-2">
                    <template v-for="child in category.children" :key="child.id">
                      <div class="category-item" :class="{'bg-primary/10': selectedCategoryId === child.id}">
                        <div class="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer hover:bg-gray-100" @click="selectCategory(child.id)">
                          <i class="fa" :class="child.children && child.children.length ? (child.expanded ? 'fa-chevron-down' : 'fa-chevron-right') : 'fa-folder-o'"></i>
                          <span>{{ child.name }}</span>
                          <span class="ml-auto badge" :class="child.status === 'active' ? 'bg-success/10 text-success' : 'bg-gray-100 text-gray-600'">
                            {{ child.status === 'active' ? '启用' : '禁用' }}
                          </span>
                        </div>
                        
                        <!-- 三级栏目 -->
                        <div v-if="child.expanded && child.children && child.children.length" class="ml-4 mt-1 border-l-2 border-gray-200 pl-2">
                          <template v-for="grandchild in child.children" :key="grandchild.id">
                            <div class="category-item" :class="{'bg-primary/10': selectedCategoryId === grandchild.id}">
                              <div class="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer hover:bg-gray-100" @click="selectCategory(grandchild.id)">
                                <i class="fa fa-folder-o"></i>
                                <span>{{ grandchild.name }}</span>
                                <span class="ml-auto badge" :class="grandchild.status === 'active' ? 'bg-success/10 text-success' : 'bg-gray-100 text-gray-600'">
                                  {{ grandchild.status === 'active' ? '启用' : '禁用' }}
                                </span>
                              </div>
                            </div>
                          </template>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </template>
              
              <div v-if="filteredCategoryTree.length === 0" class="text-center py-8 text-gray-500">
                <i class="fa fa-folder-open-o text-2xl mb-2"></i>
                <p>暂无栏目数据</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 栏目详情 -->
      <div class="lg:col-span-2">
        <div class="card h-full">
          <div v-if="selectedCategory">
            <div class="p-4 border-b border-gray-100 flex justify-between items-center">
              <h3 class="font-medium">栏目详情</h3>
              <div class="flex gap-2">
                <button class="btn btn-secondary text-sm px-3" @click="showAddCategoryDialog(selectedCategory.id)">
                  <i class="fa fa-plus"></i>
                  <span>添加子栏目</span>
                </button>
                <button class="btn btn-secondary text-sm px-3" @click="showEditCategoryDialog">
                  <i class="fa fa-pencil"></i>
                  <span>编辑</span>
                </button>
                <button class="btn btn-danger text-sm px-3" @click="confirmDeleteCategory">
                  <i class="fa fa-trash"></i>
                  <span>删除</span>
                </button>
              </div>
            </div>
            
            <div class="p-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h4 class="text-sm font-medium text-gray-500 mb-4">基本信息</h4>
                  
                  <div class="space-y-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">栏目名称</label>
                      <p class="text-gray-900">{{ selectedCategory.name }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">栏目类型</label>
                      <p class="text-gray-900">{{ getCategoryTypeName(selectedCategory.type) }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">父级栏目</label>
                      <p class="text-gray-900">{{ selectedCategory.parentId === 0 ? '无（顶级栏目）' : findCategoryName(selectedCategory.parentId) }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">所属站点</label>
                      <p class="text-gray-900">{{ findSiteName(selectedCategory.siteId) }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                      <p :class="selectedCategory.status === 'active' ? 'text-success' : 'text-gray-500'">
                        {{ selectedCategory.status === 'active' ? '启用' : '禁用' }}
                      </p>
                    </div>
                  </div>
                </div>
                
                <div>
                  <h4 class="text-sm font-medium text-gray-500 mb-4">高级信息</h4>
                  
                  <div class="space-y-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">栏目别名</label>
                      <p class="text-gray-900">{{ selectedCategory.alias || '-' }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">访问路径</label>
                      <p class="text-gray-900">{{ selectedCategory.path || '-' }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
                      <p class="text-gray-900">{{ selectedCategory.sortOrder }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                      <p class="text-gray-900">{{ selectedCategory.createTime }}</p>
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">最后修改</label>
                      <p class="text-gray-900">{{ selectedCategory.updateTime }}</p>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="mt-6 pt-6 border-t border-gray-100">
                <h4 class="text-sm font-medium text-gray-500 mb-4">栏目内容</h4>
                
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">栏目描述</label>
                    <p class="text-gray-900 whitespace-pre-line">{{ selectedCategory.description || '无描述' }}</p>
                  </div>
                  
                  <div v-if="selectedCategory.type === 'link'">
                    <label class="block text-sm font-medium text-gray-700 mb-1">跳转链接</label>
                    <p class="text-gray-900">{{ selectedCategory.linkUrl || '-' }}</p>
                  </div>
                </div>
              </div>
              
              <div class="mt-6 pt-6 border-t border-gray-100">
                <h4 class="text-sm font-medium text-gray-500 mb-4">统计信息</h4>
                
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div class="p-4 bg-gray-50 rounded-lg">
                    <p class="text-sm text-gray-500">包含子栏目</p>
                    <p class="text-xl font-bold mt-1">{{ selectedCategory.subCount || 0 }}</p>
                  </div>
                  <div class="p-4 bg-gray-50 rounded-lg">
                    <p class="text-sm text-gray-500">内容数量</p>
                    <p class="text-xl font-bold mt-1">{{ selectedCategory.contentCount || 0 }}</p>
                  </div>
                  <div class="p-4 bg-gray-50 rounded-lg">
                    <p class="text-sm text-gray-500">访问量</p>
                    <p class="text-xl font-bold mt-1">{{ selectedCategory.viewCount || 0 }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="flex flex-col items-center justify-center h-[calc(100vh-320px)] text-center p-6">
            <div class="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
              <i class="fa fa-folder-open-o text-2xl text-gray-400"></i>
            </div>
            <h3 class="text-lg font-medium mb-2">未选择栏目</h3>
            <p class="text-gray-500 max-w-md">
              请从左侧栏目结构中选择一个栏目查看详情，或点击"新增栏目"按钮创建新栏目
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 新增/编辑栏目对话框 -->
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="categoryDialogVisible">
      <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
          <h3 class="text-xl font-bold">{{ isEditMode ? '编辑栏目' : '新增栏目' }}</h3>
          <button class="text-gray-400 hover:text-gray-600" @click="closeCategoryDialog">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="p-6 space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">栏目名称 <span class="text-danger">*</span></label>
              <input 
                type="text" 
                class="form-input" 
                v-model="categoryForm.name"
                placeholder="请输入栏目名称"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属站点 <span class="text-danger">*</span></label>
              <select class="form-input" v-model="categoryForm.siteId">
                <option value="">请选择站点</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">栏目类型 <span class="text-danger">*</span></label>
              <select class="form-input" v-model="categoryForm.type">
                <option value="">请选择栏目类型</option>
                <option value="article">文章栏目</option>
                <option value="product">产品栏目</option>
                <option value="page">单页栏目</option>
                <option value="link">链接栏目</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">父级栏目</label>
              <select class="form-input" v-model="categoryForm.parentId">
                <option value="0">无（顶级栏目）</option>
                <option 
                  v-for="category in filteredParentCategories" 
                  :key="category.id" 
                  :value="category.id"
                  :disabled="category.id === currentEditingId"
                >
                  {{ getCategoryIndent(category.level) }}{{ category.name }}
                </option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">栏目别名</label>
              <input 
                type="text" 
                class="form-input" 
                v-model="categoryForm.alias"
                placeholder="用于URL和标识，建议使用英文和数字"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
              <input 
                type="number" 
                class="form-input" 
                v-model="categoryForm.sortOrder"
                min="0"
                placeholder="数字越小越靠前"
              >
            </div>
            
            <div v-if="categoryForm.type === 'link'">
              <label class="block text-sm font-medium text-gray-700 mb-1">跳转链接 <span class="text-danger">*</span></label>
              <input 
                type="text" 
                class="form-input" 
                v-model="categoryForm.linkUrl"
                placeholder="请输入链接地址，如http://example.com"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
              <select class="form-input" v-model="categoryForm.status">
                <option value="active">启用</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">栏目描述</label>
            <textarea 
              class="form-input h-24" 
              v-model="categoryForm.description"
              placeholder="请输入栏目描述信息"
            ></textarea>
          </div>
        </div>
        
        <div class="p-6 border-t border-gray-100 flex justify-end gap-3">
          <button class="btn btn-secondary" @click="closeCategoryDialog">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-primary" @click="saveCategory">
            <i class="fa fa-check"></i>
            <span>保存</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
  
  <!-- 删除确认对话框 -->
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="deleteDialogVisible">
      <div class="bg-white rounded-xl w-full max-w-md">
        <div class="p-6 text-center">
          <div class="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-exclamation-triangle text-2xl text-danger"></i>
          </div>
          <h3 class="text-xl font-bold mb-2">确认删除</h3>
          <p class="text-gray-500">
            您确定要删除栏目"{{ selectedCategory?.name }}"吗？
            <template v-if="selectedCategory?.subCount > 0">
              该栏目包含{{ selectedCategory.subCount }}个子栏目，将一并删除。
            </template>
          </p>
        </div>
        
        <div class="p-4 border-t border-gray-100 flex justify-center gap-3">
          <button class="btn btn-secondary" @click="deleteDialogVisible = false">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-danger" @click="deleteCategory">
            <i class="fa fa-trash"></i>
            <span>确认删除</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

// 站点数据
const sites = ref([
  { id: 1, name: '时尚服装商城' },
  { id: 2, name: '科技有限公司官网' },
  { id: 3, name: '教育培训平台' }
])

// 栏目数据
const categories = ref([
  {
    id: 1,
    name: '首页',
    type: 'page',
    parentId: 0,
    siteId: 1,
    alias: 'home',
    path: '/',
    status: 'active',
    sortOrder: 1,
    description: '网站首页',
    createTime: '2023-05-10',
    updateTime: '2023-06-15',
    subCount: 0,
    contentCount: 1,
    viewCount: 12500
  },
  {
    id: 2,
    name: '产品中心',
    type: 'product',
    parentId: 0,
    siteId: 1,
    alias: 'products',
    path: '/products',
    status: 'active',
    sortOrder: 2,
    description: '展示公司所有产品',
    createTime: '2023-05-10',
    updateTime: '2023-06-10',
    subCount: 3,
    contentCount: 45,
    viewCount: 8750
  },
  {
    id: 3,
    name: '男装系列',
    type: 'product',
    parentId: 2,
    siteId: 1,
    alias: 'men',
    path: '/products/men',
    status: 'active',
    sortOrder: 1,
    description: '男士服装系列',
    createTime: '2023-05-12',
    updateTime: '2023-06-05',
    subCount: 0,
    contentCount: 15,
    viewCount: 3200
  },
  {
    id: 4,
    name: '女装系列',
    type: 'product',
    parentId: 2,
    siteId: 1,
    alias: 'women',
    path: '/products/women',
    status: 'active',
    sortOrder: 2,
    description: '女士服装系列',
    createTime: '2023-05-12',
    updateTime: '2023-06-08',
    subCount: 0,
    contentCount: 20,
    viewCount: 4500
  },
  {
    id: 5,
    name: '配饰系列',
    type: 'product',
    parentId: 2,
    siteId: 1,
    alias: 'accessories',
    path: '/products/accessories',
    status: 'active',
    sortOrder: 3,
    description: '服装配饰系列',
    createTime: '2023-05-15',
    updateTime: '2023-06-01',
    subCount: 0,
    contentCount: 10,
    viewCount: 1050
  },
  {
    id: 6,
    name: '品牌故事',
    type: 'article',
    parentId: 0,
    siteId: 1,
    alias: 'story',
    path: '/story',
    status: 'active',
    sortOrder: 3,
    description: '品牌相关资讯',
    createTime: '2023-05-20',
    updateTime: '2023-05-25',
    subCount: 2,
    contentCount: 12,
    viewCount: 2300
  },
  {
    id: 7,
    name: '企业动态',
    type: 'article',
    parentId: 6,
    siteId: 1,
    alias: 'news',
    path: '/story/news',
    status: 'active',
    sortOrder: 1,
    description: '公司最新动态',
    createTime: '2023-05-22',
    updateTime: '2023-06-18',
    subCount: 0,
    contentCount: 8,
    viewCount: 1500
  },
  {
    id: 8,
    name: '联系我们',
    type: 'page',
    parentId: 0,
    siteId: 1,
    alias: 'contact',
    path: '/contact',
    status: 'active',
    sortOrder: 4,
    description: '联系方式和地图',
    createTime: '2023-05-25',
    updateTime: '2023-05-25',
    subCount: 0,
    contentCount: 1,
    viewCount: 950
  },
  {
    id: 9,
    name: '官网首页',
    type: 'page',
    parentId: 0,
    siteId: 2,
    alias: 'home',
    path: '/',
    status: 'active',
    sortOrder: 1,
    description: '科技公司官网首页',
    createTime: '2023-06-01',
    updateTime: '2023-06-12',
    subCount: 0,
    contentCount: 1,
    viewCount: 6800
  }
])

// 筛选条件
const filters = reactive({
  siteId: '',
  type: '',
  status: ''
})

// 当前选中的栏目ID
const selectedCategoryId = ref(null)

// 栏目对话框状态
const categoryDialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditingId = ref(null)
const categoryForm = reactive({
  name: '',
  siteId: '',
  type: '',
  parentId: 0,
  alias: '',
  sortOrder: 0,
  linkUrl: '',
  status: 'active',
  description: ''
})

// 删除对话框状态
const deleteDialogVisible = ref(false)

// 构建树形结构的栏目数据
const categoryTree = computed(() => {
  // 过滤站点
  const filteredBySite = filters.siteId 
    ? categories.value.filter(cat => cat.siteId == filters.siteId)
    : [...categories.value]
  
  // 构建树形结构
  const tree = []
  const map = {}
  
  // 先创建节点映射
  filteredBySite.forEach(cat => {
    map[cat.id] = { ...cat, children: [], expanded: false, level: 0 }
  })
  
  // 构建树形结构
  filteredBySite.forEach(cat => {
    const node = map[cat.id]
    if (cat.parentId === 0) {
      tree.push(node)
    } else if (map[cat.parentId]) {
      map[cat.parentId].children.push(node)
      node.level = map[cat.parentId].level + 1
    }
  })
  
  // 按排序号排序
  const sortChildren = (nodes) => {
    nodes.sort((a, b) => a.sortOrder - b.sortOrder)
    nodes.forEach(node => {
      if (node.children && node.children.length) {
        sortChildren(node.children)
      }
    })
  }
  
  sortChildren(tree)
  
  return tree
})

// 应用类型和状态筛选的栏目树
const filteredCategoryTree = computed(() => {
  // 递归筛选节点
  const filterNodes = (nodes) => {
    return nodes
      .filter(node => {
        // 应用类型筛选
        const typeMatch = !filters.type || node.type === filters.type
        // 应用状态筛选
        const statusMatch = !filters.status || node.status === filters.status
        return typeMatch && statusMatch
      })
      .map(node => {
        // 递归处理子节点
        const filteredChildren = filterNodes(node.children || [])
        return { ...node, children: filteredChildren }
      })
  }
  
  return filterNodes(categoryTree.value)
})

// 当前选中的栏目
const selectedCategory = computed(() => {
  if (!selectedCategoryId.value) return null
  return findCategoryById(selectedCategoryId.value)
})

// 可作为父级的栏目列表（排除当前编辑的栏目）
const filteredParentCategories = computed(() => {
  // 只包含当前选中站点的栏目
  let candidates = filters.siteId 
    ? categories.value.filter(cat => cat.siteId == filters.siteId)
    : [...categories.value]
  
  // 递归获取所有子栏目ID，用于排除
  const getAllChildrenIds = (parentId) => {
    const children = categories.value.filter(cat => cat.parentId == parentId)
    let ids = []
    children.forEach(child => {
      ids.push(child.id)
      ids = [...ids, ...getAllChildrenIds(child.id)]
    })
    return ids
  }
  
  // 如果是编辑模式，排除自身和所有子栏目
  if (isEditMode.value && currentEditingId.value) {
    const childrenIds = getAllChildrenIds(currentEditingId.value)
    candidates = candidates.filter(cat => 
      cat.id !== currentEditingId.value && !childrenIds.includes(cat.id)
    )
  }
  
  return candidates
})

// 初始化
onMounted(() => {
  // 默认选中第一个栏目
  if (categories.value.length > 0) {
    selectedCategoryId.value = categories.value[0].id
  }
})

// 加载栏目（模拟API调用）
const loadCategories = () => {
  // 实际项目中这里会调用API加载指定站点的栏目
  selectedCategoryId.value = null
  // 延迟模拟加载
  setTimeout(() => {
    if (filteredCategoryTree.value.length > 0) {
      selectedCategoryId.value = filteredCategoryTree.value[0].id
    }
  }, 300)
}

// 筛选栏目
const filterCategories = () => {
  if (selectedCategoryId.value && !findCategoryInTree(selectedCategoryId.value, filteredCategoryTree.value)) {
    selectedCategoryId.value = filteredCategoryTree.value.length > 0 ? filteredCategoryTree.value[0].id : null
  }
}

// 刷新栏目
const refreshCategories = () => {
  // 实际项目中这里会调用API刷新栏目数据
  const currentId = selectedCategoryId.value
  loadCategories()
  // 尝试保持选中状态
  setTimeout(() => {
    if (currentId && findCategoryInTree(currentId, filteredCategoryTree.value)) {
      selectedCategoryId.value = currentId
    }
  }, 300)
}

// 选择栏目
const selectCategory = (id) => {
  selectedCategoryId.value = id
  
  // 展开父节点
  const expandParentNodes = (nodeId) => {
    const node = findCategoryById(nodeId)
    if (node && node.parentId !== 0) {
      const parentNode = findNodeInTree(node.parentId, categoryTree.value)
      if (parentNode) {
        parentNode.expanded = true
        expandParentNodes(node.parentId)
      }
    }
  }
  
  expandParentNodes(id)
}

// 显示新增栏目对话框
const showAddCategoryDialog = (parentId = 0) => {
  isEditMode.value = false
  currentEditingId.value = null
  categoryDialogVisible.value = true
  
  // 重置表单
  Object.assign(categoryForm, {
    name: '',
    siteId: filters.siteId || '',
    type: '',
    parentId: parentId,
    alias: '',
    sortOrder: 0,
    linkUrl: '',
    status: 'active',
    description: ''
  })
}

// 显示编辑栏目对话框
const showEditCategoryDialog = () => {
  if (!selectedCategory.value) return
  
  isEditMode.value = true
  currentEditingId.value = selectedCategory.value.id
  categoryDialogVisible.value = true
  
  // 填充表单
  const cat = selectedCategory.value
  Object.assign(categoryForm, {
    name: cat.name,
    siteId: cat.siteId,
    type: cat.type,
    parentId: cat.parentId,
    alias: cat.alias,
    sortOrder: cat.sortOrder,
    linkUrl: cat.linkUrl || '',
    status: cat.status,
    description: cat.description || ''
  })
}

// 关闭栏目对话框
const closeCategoryDialog = () => {
  categoryDialogVisible.value = false
}

// 保存栏目
const saveCategory = () => {
  // 简单验证
  if (!categoryForm.name) {
    alert('请输入栏目名称')
    return
  }
  
  if (!categoryForm.siteId) {
    alert('请选择所属站点')
    return
  }
  
  if (!categoryForm.type) {
    alert('请选择栏目类型')
    return
  }
  
  if (categoryForm.type === 'link' && !categoryForm.linkUrl) {
    alert('请输入跳转链接')
    return
  }
  
  if (isEditMode.value) {
    // 编辑现有栏目
    const index = categories.value.findIndex(cat => cat.id === currentEditingId.value)
    if (index !== -1) {
      categories.value[index] = {
        ...categories.value[index],
        name: categoryForm.name,
        siteId: categoryForm.siteId,
        type: categoryForm.type,
        parentId: categoryForm.parentId,
        alias: categoryForm.alias,
        sortOrder: categoryForm.sortOrder,
        linkUrl: categoryForm.linkUrl,
        status: categoryForm.status,
        description: categoryForm.description,
        updateTime: new Date().toLocaleDateString()
      }
    }
  } else {
    // 新增栏目
    const newId = Math.max(...categories.value.map(cat => cat.id), 0) + 1
    categories.value.push({
      id: newId,
      name: categoryForm.name,
      siteId: categoryForm.siteId,
      type: categoryForm.type,
      parentId: categoryForm.parentId,
      alias: categoryForm.alias,
      path: generateCategoryPath(categoryForm),
      status: categoryForm.status,
      sortOrder: categoryForm.sortOrder,
      linkUrl: categoryForm.linkUrl,
      description: categoryForm.description,
      createTime: new Date().toLocaleDateString(),
      updateTime: new Date().toLocaleDateString(),
      subCount: 0,
      contentCount: 0,
      viewCount: 0
    })
    
    // 选中新栏目
    selectedCategoryId.value = newId
    
    // 更新父栏目子栏目数量
    if (categoryForm.parentId !== 0) {
      const parentIndex = categories.value.findIndex(cat => cat.id === categoryForm.parentId)
      if (parentIndex !== -1) {
        categories.value[parentIndex].subCount = (categories.value[parentIndex].subCount || 0) + 1
      }
    }
  }
  
  // 关闭对话框
  categoryDialogVisible.value = false
  alert(isEditMode.value ? '栏目更新成功' : '栏目创建成功')
}

// 确认删除栏目
const confirmDeleteCategory = () => {
  if (selectedCategory.value) {
    deleteDialogVisible.value = true
  }
}

// 删除栏目
const deleteCategory = () => {
  if (!selectedCategory.value) return
  
  // 递归获取所有子栏目ID
  const getAllChildrenIds = (parentId) => {
    const children = categories.value.filter(cat => cat.parentId == parentId)
    let ids = [parentId]
    children.forEach(child => {
      ids = [...ids, ...getAllChildrenIds(child.id)]
    })
    return ids
  }
  
  // 获取要删除的所有栏目ID
  const idsToDelete = getAllChildrenIds(selectedCategory.value.id)
  
  // 执行删除
  categories.value = categories.value.filter(cat => !idsToDelete.includes(cat.id))
  
  // 更新父栏目子栏目数量
  if (selectedCategory.value.parentId !== 0) {
    const parentIndex = categories.value.findIndex(cat => cat.id === selectedCategory.value.parentId)
    if (parentIndex !== -1) {
      // 计算剩余子栏目数量
      const remainingChildren = categories.value.filter(cat => cat.parentId == selectedCategory.value.parentId)
      categories.value[parentIndex].subCount = remainingChildren.length
    }
  }
  
  // 重置选中状态
  selectedCategoryId.value = filteredCategoryTree.value.length > 0 ? filteredCategoryTree.value[0].id : null
  
  // 关闭对话框
  deleteDialogVisible.value = false
  alert('栏目已删除')
}

// 辅助函数：查找栏目
const findCategoryById = (id) => {
  return categories.value.find(cat => cat.id === id) || null
}

// 辅助函数：在树形结构中查找节点
const findNodeInTree = (id, tree) => {
  for (const node of tree) {
    if (node.id === id) {
      return node
    }
    if (node.children && node.children.length) {
      const found = findNodeInTree(id, node.children)
      if (found) return found
    }
  }
  return null
}

// 辅助函数：检查栏目是否在树形结构中
const findCategoryInTree = (id, tree) => {
  return !!findNodeInTree(id, tree)
}

// 辅助函数：获取栏目名称
const findCategoryName = (id) => {
  const category = findCategoryById(id)
  return category ? category.name : '未知栏目'
}

// 辅助函数：获取站点名称
const findSiteName = (id) => {
  const site = sites.value.find(s => s.id == id)
  return site ? site.name : '未知站点'
}

// 辅助函数：获取栏目类型名称
const getCategoryTypeName = (type) => {
  const types = {
    'article': '文章栏目',
    'product': '产品栏目',
    'page': '单页栏目',
    'link': '链接栏目'
  }
  return types[type] || '未知类型'
}

// 辅助函数：生成栏目路径
const generateCategoryPath = (form) => {
  if (form.parentId === 0) {
    return form.alias ? `/${form.alias}` : `/${form.name.toLowerCase().replace(/\s+/g, '-')}`
  } else {
    const parent = findCategoryById(form.parentId)
    if (parent) {
      return form.alias 
        ? `${parent.path}/${form.alias}` 
        : `${parent.path}/${form.name.toLowerCase().replace(/\s+/g, '-')}`
    }
    return form.alias ? `/${form.alias}` : `/${form.name.toLowerCase().replace(/\s+/g, '-')}`
  }
}

// 辅助函数：生成栏目缩进
const getCategoryIndent = (level) => {
  return '　'.repeat(level) // 使用全角空格实现缩进
}
</script>

<style scoped>
.category-item {
  transition: background-color 0.2s;
}
</style>